from django.shortcuts import render
from django.core.cache import cache
from utils.common_response import APIResponse
# Create your views here.

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from .serializer import BannerSerializer
from .models import Banner
from utils.common_mixin import CommonListModelMixin as ListModelMixin
from django.conf import settings


class BannerView(GenericViewSet,ListModelMixin):
    queryset = Banner.objects.all().filter(is_delete=False,is_show=True).order_by(('orders'))[:settings.BANNER_COUNT]
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):
        '''
          1 先去缓存中查一下有没有数据
          2 如果有，直接返回，不走父类的list了(list在走数据库)
          3 如果没有，走父类list，查询数据库
          4 把返回的数据，放到缓存中
        '''

        data = cache.get('home_banner_list')
        print(1)
        if not data:  # 缓存中没有
            print('走了数据库')
            res = super().list(request, *args, **kwargs)  # 查询数据库
            # 返回的数据，放到缓存中
            data = res.data.get('data')  # {code:100,msg:成功，data:[{},{}]}
            cache.set('home_banner_list', data)
        return APIResponse(data=data)

